import Schema, { Rules, Values } from "async-validator";
import { Context } from "koa";

/**
 * @description 表单校验
 * @param {Context} ctx 上下文
 * @param {Rules} rules 校验规则
 * @param {boolean} flag 是否返回完整的的错误信息
 * @return {*}
 */
async function validate<T extends Values>(ctx: Context, rules: Rules, flag: boolean = false): Promise<{ data: T, error: any | null }> {
  const validator = new Schema(rules)
  let data: any = {}

  switch (ctx.method) {
    case "GET": break;
    case "POST": data = getFormData(ctx); break;
    case "PUT": data = getFormData(ctx); break;
    case "DELETE": data = getFormData(ctx); break;

  }
  return await validator.validate(data).then((data) => {
    return {
      data: data as T,
      error: null
    }
  }).catch(err => {
    if (flag) {
      return {
        data: {} as T,
        error: err
      }
    }
    return {
      data: {} as T,
      error: err.errors[0].message
    }
  })
}

function getFormData(ctx: Context) {
  // console.log(JSON.stringify(ctx.request.body))
  return ctx.request.body
}

export default validate
